<template>
  <view class="CoursePage">
    <view class="top-wrap">
      <button type="primary" size="mini" @click="clickHandler">添加新的记录</button>
    </view>
    <uni-list>
      <uni-list-item
        :title="item.name"
        :note="item.classTime"
        v-for="item in recordList"
        :key="item.id"
        clickable
        @click="listItemClickHandler(item)"
      >
      </uni-list-item>
    </uni-list>
  </view>
  <view>
    <uni-popup ref="popup" type="center">
      <view class="popup-container">
        <uni-forms ref="form" :model="formData" :rules="rules">
          <uni-forms-item required label="课程记录标题" name="name">
            <uni-easyinput
              v-model="formData.name"
              type="text"
              placeholder="请填写上课记录标题"
            />
          </uni-forms-item>
          <uni-forms-item required label="上课时间" name="classTime">
            <uni-datetime-picker type="datetime" v-model="formData.classTime" />
          </uni-forms-item>
        </uni-forms>
        <button type="primary" @click="newRecordHandler">提交</button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { getRecordListByCourseId, postNewRecord } from "@/api/courseApi";
import { onLoad } from "@dcloudio/uni-app";
import {ruleRequired,phone} from "@/utils/rules"
const rules ={

    name: {
      rules:[ruleRequired("请填写上课记录标题")]
    },
    classTime: {
      rules:[ruleRequired("请选择上课时间")]
    },
}
const prop=defineProps(["id"])
const recordList = ref([]);
const clickHandler = () => {
   popup.value.open()
};
const formData = ref({
  courseId: "",
  name: "",
  classTime: "",
});
const popup=ref(null)
const form=ref(null)
const courseId = ref(-1);
const getRecordListData = () => {
  getRecordListByCourseId({ id: courseId.value }).then((res) => {
    if (Array.isArray(res.data)) {
      recordList.value = res.data;
    }
  });
};
const newRecordHandler = () => {
    form.value.validate().then(res=>{
   postNewRecord(formData.value).then((res) => {
    msgSuccess("添加记录成功");
      getRecordListData()
    formData.value.name=""
    formData.value.classTime=""
    popup.value.close()
  });
  })
};
const listItemClickHandler=(record)=>{
  uni.navigateTo({
    url:`/pages/RecordDetail/RecordDetail?id=${record.id}&courseId=${prop.id}`
  })
}
onLoad(() => {
  const id = getRouterParam().id;
  courseId.value = id;
  formData.value.courseId = id;
  getRecordListData()
});
</script>

<style lang="scss" scoped>
.popup-container {
  width: 80vw;
  height: 50vh;
  padding: 30rpx;
  background-color: #fff;
}
.top-wrap{
  display: flex;
  width: 100%;
  height: 80rpx;
  justify-content: space-between;
  align-items: center;
}
</style>
